package com.wedistudio.slideshare.service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.simpleframework.xml.Serializer;

import com.wedistudio.android.framework.fetcher.URLParams;
import com.wedistudio.android.framework.pool.PoolFactory;
import com.wedistudio.android.framework.service.Service;
import com.wedistudio.android.framework.service.ServiceException;
import com.wedistudio.android.framework.service.ServiceRequestConverter;
import com.wedistudio.android.framework.service.ServiceResponseConverter;
import com.wedistudio.slideshare.SlideshareUtils;
import com.wedistudio.slideshare.xml.Slideshow;
import com.wedistudio.slideshare.xml.User;
import com.wedistudio.slidesprovider.Author;
import com.wedistudio.slidesprovider.SearchWindow;
import com.wedistudio.slidesprovider.Slide;
import com.wedistudio.slidesprovider.Slides;

public class GetSlidesByAuthor extends Service<SearchWindow<Author>, Slides> {

	static public GetSlidesByAuthor create() {
		return new GetSlidesByAuthor();
	}

	private static String GET_SLIDESHOW_BY_USER = "get_slideshows_by_user";

	private GetSlidesByAuthor() {
		setRequestConverter(new ServiceRequestConverter<SearchWindow<Author>>() {

			@Override
			public List<URLParams> convert(SearchWindow<Author> request)
					throws ServiceException {
				List<URLParams> result = new ArrayList<URLParams>();
				URLParams params = SlideshareUtils
						.buildURLParams(GET_SLIDESHOW_BY_USER);

				params.addParam("username_for", request.getObj().getName());
				params.addParam("detailed", "1");
				params.addParam("offset", "" + request.getOffset());
				params.addParam("limit", "" + request.getLimit());
				result.add(params);
				return result;
			}
		});

		setResponseConverter(new ServiceResponseConverter<Slides>() {

			@Override
			public Slides convert(Map<URLParams, String> raw)
					throws ServiceException {
				Serializer serializer = null;
				try {
					String xml = null;
					for (Map.Entry<URLParams, String> entry : raw.entrySet()) {
						xml = entry.getValue();
						SlideshareUtils.checkResponse(xml);
					}

					serializer = PoolFactory.get(Serializer.class);

					final User user = serializer.read(User.class, xml);

					Slides result = new Slides("author:" + user.Name,
							user.NbSlide, 0);

					for (final Slideshow slideshow : user.slideshows) {
						Slide slide = slideshow.getSlide();
						result.add(slide);
					}
					return result;

				} catch (ServiceException e) {
					throw e;
				} catch (Throwable e) {
					throw new ServiceException(e);
				} finally {
					PoolFactory.release(serializer, Serializer.class);
				}

			}
		});
	}
}
